package sy.service.impl;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import sy.model.AppAccountVerificatCode;
import sy.model.AppEquipment;
import sy.model.AppFunction;
import sy.model.SysAccount;
import sy.model.SysBuilding;
import sy.model.SysOwnerRenterMapping;
import sy.model.SysProject;
import sy.model.SysProjectOwnerMapping;
import sy.model.SysRole;
import sy.model.SysUnit;
import sy.model.SysUser;
import sy.model.SysUserUnitMapping;
import sy.service.AppAccountVerificatCodeServiceI;
import sy.service.AppBaseServiceI;
import sy.service.AppEquipmentServiceI;
import sy.service.AppFunctionServiceI;
import sy.service.SysAccountServiceI;
import sy.service.SysOwnerRenterMappingServiceI;
import sy.service.SysProjectOwnerMappingServiceI;
import sy.service.SysRoleServiceI;
import sy.service.SysUserServiceI;
import sy.service.SysUserUnitMappingServiceI;
import sy.util.DateUtil;
import sy.util.Encrypt;
import sy.util.HttpUtils;
import sy.util.JGpush;
import sy.util.ResultJson;
import sy.util.SendMessage;
@Service("appBaseService")
public class AppBaseServiceImpl implements AppBaseServiceI{
	@Autowired
	AppAccountVerificatCodeServiceI appAccountVerificatCodeService;
	@Autowired
	SysAccountServiceI sysAccountService;
	@Autowired
	SysUserServiceI sysUserService;
	@Autowired
	SysProjectOwnerMappingServiceI sysProjectOwnerMappingService;
	@Autowired
	AppEquipmentServiceI appEquipmentService;
	@Autowired
	AppFunctionServiceI appFunctionService;
	@Autowired
	SysRoleServiceI sysRoleService;
	@Autowired
	SysUserUnitMappingServiceI sysUserUnitMappingService;
	@Autowired
	SysOwnerRenterMappingServiceI sysOwnerRenterMappingService;

	@Override
	public ResultJson getVerificatCode(String telephone) {
		/**
		 * 1.查找该手机是否已注册过；
		 * 2.没有注册，则先生成一个6位数的验证码,写入AppAccountVerificatCode表，再调用短信发送接口发送到传过来的手机
		 */
		ResultJson resultJson = new ResultJson();
		//List<SysAccount> sysAccountList = sysAccountService.listSysAccountByKey(telephone);
		/*		if (!sysAccountList.isEmpty()) {
			resultJson.setState(false);
			resultJson.setErrorCode(-5);
			resultJson.setMessage("该账号已注册过！");
		} else {*/
		int radomInt = new Random().nextInt(999999);
		String verificatCode = String.valueOf(radomInt);
		do{
			radomInt = new Random().nextInt(999999);
		}while(verificatCode.length()<6);
		Date creatTime = new Date();
		boolean flag = appAccountVerificatCodeService.judgeTelephoneIsExist(telephone);//判断该手机号是否有发送过短信，有则更新验证码，没有则新插入数据
		if (flag) {
			Serializable i = appAccountVerificatCodeService.updateAppAccountVerificatCode(telephone, verificatCode, creatTime);
		} else {
			AppAccountVerificatCode appAccountVerificatCode = new AppAccountVerificatCode();
			appAccountVerificatCode.setAccount(telephone);
			appAccountVerificatCode.setVerificatCode(verificatCode);
			appAccountVerificatCode.setCreateTime(creatTime);
			Serializable i = appAccountVerificatCodeService.save(appAccountVerificatCode);
		}
		/**
		 * 最后调用接口发送短信
		 */
		String sendMessageFlag = SendMessage.sendFlag(telephone,verificatCode);
		if ("0".equals(sendMessageFlag)) {
			resultJson.setState(false);
			resultJson.setErrorCode(-4);
			resultJson.setMessage("短信发送失败");
		} else {
			resultJson.setState(true);
			resultJson.setErrorCode(200);
			resultJson.setMessage("短信发送成功");
		}
		//}
		return resultJson;
	}
	@Override
	public ResultJson testVerificatCode(String telephone, String verificatCode) {
		/**
		 * 根据传来的手机号和验证码判断该验证码是否有效（即该验证码从生成时间到当前时间不超过半小时）
		 */
		ResultJson resultJson = new ResultJson();
		List<AppAccountVerificatCode> list = appAccountVerificatCodeService.getAppAccountVerificatCode(telephone, verificatCode);
		if (list.isEmpty()) {
			resultJson.setState(false);
			resultJson.setErrorCode(111);
			resultJson.setMessage("该验证码无效！");
		} else {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String creatTime = sdf.format(list.get(0).getCreateTime());
			try {
				long differTime = DateUtil.differTime(creatTime, sdf.format(new Date()));
				if(differTime>5){
					resultJson.setState(false);
					resultJson.setErrorCode(110);
					resultJson.setMessage("验证码已过期");
				}else{
					resultJson.setState(true);
					resultJson.setErrorCode(200);
					resultJson.setMessage("验证码正确");
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson register(String telephone, String password) {
		// TODO Auto-generated method stub
		/**
		 * 根据传过来的手机号和密码写入账号表（sysAccount）
		 * 1.先判断该手机号码是否已经注册
		 * 2.注册过返回提示信息，没注册过写入账号表
		 */
		ResultJson resultJson = new ResultJson();
		SysAccount account = (SysAccount) sysAccountService.findByName(telephone);
		if (account != null){
			resultJson.setState(false);
			resultJson.setErrorCode(-5);
			resultJson.setMessage("您已注册过，请直接登录");
		} else {
			SysAccount sysAccount = new SysAccount();
			sysAccount.setName(telephone);
			sysAccount.setPassword(password);
			sysAccount.setId(UUID.randomUUID().toString());
			sysAccount.setToken(UUID.randomUUID().toString());
			Serializable result = sysAccountService.save(sysAccount);
			resultJson.setState(true);
			resultJson.setErrorCode(200);
			resultJson.setMessage("注册成功");
		}
		return resultJson;
	}
	@Override
	public ResultJson login(String telephone, String password) {
		ResultJson resultJson = new ResultJson();
		SysAccount sysAccount = null;
		/**
		 * 判断是否存在此账户
		 */
		sysAccount = (SysAccount) sysAccountService.findByName(telephone);
		if (sysAccount != null) {
			/**
			 * 判断用户名密码是否正确
			 */
			sysAccount = (SysAccount) sysAccountService.login(telephone, password);
			if (sysAccount != null) {
				Map<String, Object> resultMap = new HashMap<String, Object>();
				/**
				 * 根据账户id获取用户基本信息
				 * sysUser=null或者sysUser的isOwner=n表示该账户是同住人
				 * sysUser!=null时表示该账户（同住人）已拥有业主权限
				 */
				SysUser sysUser = sysUserService.getSysUserByAccount(sysAccount.getId());
				resultMap.put("sysUser", sysUser);
				/**
				 * 获取拥有的单元，楼栋，项目信息判断依据：
				 * 1.若该账户不是业主，则去查找业主同住人中间表，看看该账户有没有绑定业主，绑定则拉取所绑定业主所拥有的房址信息，没有绑定不返回，
				 *   开门时移动端应先根据有没有返回相应的房址信息去提示用户有没有权限开门
				 * 2.若是业主，直接拉取所拥有的房址信息
				 */
				if (sysUser != null) {
					List<SysUnit> unitList =  new ArrayList<SysUnit>();
					List<SysBuilding> buildingList =  new ArrayList<SysBuilding>();
					List<SysProject> projectList =  new ArrayList<SysProject>();
					List<String> ccProjectCodeList =  new ArrayList<String>();
					if ("y".equals(sysUser.getIsOwner())) {//是业主
						List<SysUserUnitMapping> userAddressList = sysUserUnitMappingService.listSysUserUnitMappingByOwnerId(sysUser.getId());
						/***********得到该业主所拥有的单元***********/
						for(SysUserUnitMapping userUnit : userAddressList) {
							if(userUnit.getSysUnit()!=null){
								unitList.add(userUnit.getSysUnit());
							}
						}
						/***********得到该业主所拥有的楼栋***********/
						for(SysUnit unit : unitList){
							if(unit.getSysBuilding()!=null){
								buildingList.add(unit.getSysBuilding());
							}
						}
						/***********得到该业主所拥有的项目***********/
						for(SysBuilding building : buildingList) {			
							if(!ccProjectCodeList.contains(building.getSysProject().getCcProjectCode())){		
								projectList.add(building.getSysProject());
							}
							ccProjectCodeList.add(building.getSysProject().getCcProjectCode());
						}
					} else {
						/**
						 * 不是业主，则查找业主同住人中间表，看看该用户绑定了哪些业主
						 */
						List<SysOwnerRenterMapping> ORList = sysOwnerRenterMappingService.listSysOwnerRenterMappingByRentorId(sysAccount.getId());
						for(SysOwnerRenterMapping OR : ORList){
							/*****************通过accountId(业主)获取userId(业主)***********************/
							SysUser userOwner = sysUserService.getSysUserByAccount(OR.getSysAccountByOwner().getId());

							List<SysUserUnitMapping> userAddressList = sysUserUnitMappingService.listSysUserUnitMappingByOwnerId(userOwner.getId());
							/***********得到该业主所拥有的单元***********/
							for(SysUserUnitMapping userUnit : userAddressList) {
								if(userUnit.getSysUnit()!=null){
									unitList.add(userUnit.getSysUnit());
								}
							}
							/***********得到该业主所拥有的楼栋***********/
							for(SysUnit unit : unitList){
								if(unit.getSysBuilding()!=null){
									buildingList.add(unit.getSysBuilding());
								}
							}
							/***********得到该业主所拥有的项目***********/
							for(SysBuilding building : buildingList) {			
								if(!ccProjectCodeList.contains(building.getSysProject().getCcProjectCode())){		
									projectList.add(building.getSysProject());
								}
								ccProjectCodeList.add(building.getSysProject().getCcProjectCode());
							}
						}
					}
					resultMap.put("projectList", projectList);
					resultMap.put("unitList", unitList);
				}

				/*				List<SysProjectOwnerMapping> projectList = sysProjectOwnerMappingService.listSysProjectOwnerMappingByOwnerId(sysAccount.getId());
				if (!projectList.isEmpty()) {
					resultMap.put("sysProjectOwnerMapping", projectList);


					List<AppEquipment> equipmentList = appEquipmentService.listAppEquipmentByOwnerId(sysAccount.getId());
					if (!equipmentList.isEmpty()) {
						resultMap.put("appEquipment", equipmentList);
					}

				}*/
				/**
				 * 获取app所有功能
				 */
				/*				List<AppFunction> appFunctionList = appFunctionService.listAppFunction();
				if (!appFunctionList.isEmpty()){
					resultMap.put("appFunction", appFunctionList);
				}*/
				/**
				 * 更新账户登录时间，供app判断token是否过期用
				 */
				sysAccount.setLoginTime(new Date());
				resultJson.setState(true);
				resultJson.setResult(resultMap);
				resultJson.setErrorCode(200);
				resultJson.setMessage("登录成功");
			} else {
				resultJson.setState(false);
				resultJson.setMessage("用户名密码不正确，请重新输入");
				resultJson.setErrorCode(113);
			}

		}else {
			resultJson.setState(false);
			resultJson.setMessage("用户名不存在，请重新输入");
			resultJson.setErrorCode(114);
		}


		return resultJson;
	}
	@Override
	public ResultJson appLogout(String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		try {
			sysAccountService.updateLoginTime(token);
			resultJson.setErrorCode(200);
			resultJson.setMessage("登出成功！");
		} catch (Exception e) {
			System.out.println(e);
			resultJson.setErrorCode(403);
			resultJson.setMessage("网络异常，登出失败！");
		}
		return resultJson;
	}
	@Override
	public ResultJson modifyPassword(String telephone, String password) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		try {
			sysAccountService.modifyPassword(telephone, password);
			resultJson.setState(true);
			resultJson.setErrorCode(200);
			resultJson.setMessage("修改成功");
		} catch (Exception e) {
			System.out.println(e);
			resultJson.setErrorCode(403);
			resultJson.setMessage("网络异常，修改失败！");
		}
		return resultJson;
	}
	@Override
	public ResultJson jgPush(String alias, String msg, String pushToWebMsg) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		Map<String,String> param = new HashMap<>();
		param.put("key", "test");
		param.put("msg", msg);
		try{
			/*******************通知web前端**********************/
			/**
			 * pushToWebMsg模板
			 *	{"room":"coppm_data","msg":"{'videoRoom':'xxx','from':'xxxx','to':'xxx','type':'video'}"}
			 */
			if(!"".equals(pushToWebMsg) && pushToWebMsg != null){
				Map<String,String> msgParam = new HashMap<>();
				JSONObject obj = new JSONObject();
				obj.put("room", "coppm_data");
				JSONObject pushToWebMsgJson = JSONObject.parseObject(pushToWebMsg);
				obj.put("msg", pushToWebMsgJson);
				msgParam.put("msg", obj.toJSONString());
				String result = HttpUtils.sendPost("http://xhmind.com:8005/push", msgParam);
			}else{
				//JGpush.jpushIOSByAlias(param, alias);
				JGpush.jpushAndroidByAlias(param, alias);
			}
			resultJson.setState(true);
			resultJson.setErrorCode(200);
			resultJson.setMessage("推送成功");
		}catch(Exception e){
			resultJson.setState(false);
			resultJson.setErrorCode(201);
			resultJson.setMessage("系统异常，推送失败");
		}
		return resultJson;
	}
}
